package com.cskaoyan.service.wx;


import com.cskaoyan.bean.goods.Bo.BaseParamBo;
import com.cskaoyan.bean.goods.wx.ListBean;
import com.cskaoyan.bean.goods.wx.WxGoodsListData;
import com.cskaoyan.bean.goods.wx.WxGoodsRelatedData;
import com.cskaoyan.bean.param.BaseParam;
import com.cskaoyan.bean.po.*;
import com.cskaoyan.bean.wx.footprint.Foot222.*;
import com.cskaoyan.bean.wx.footprint.FootPritnByIdVo;
import com.cskaoyan.mapper.*;
import com.cskaoyan.util.UserIdUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * ClassName: WxGoodsServiceImpl
 * Description:
 * date: 2022/6/8 15:23
 *
 * @author bruce
 * @since JDK 8
 */
@Service
public class WxGoodsServiceImpl implements WxGoodsService {
    @Autowired
    MarketGoodsMapper marketGoodsMapper;

    @Autowired
    MarketCategoryMapper marketCategoryMapper;
    @Autowired
    MarketGoodsSpecificationMapper marketGoodsSpecificationMapper;
    @Autowired
    MarketIssueMapper marketIssueMapper;
    @Autowired
    MarketCommentMapper marketCommentMapper;
    @Autowired
    MarketUserMapper marketUserMapper;
    @Autowired
    MarketCollectMapper marketCollectMapper;
    @Autowired
    MarketGoodsAttributeMapper marketGoodsAttributeMapper;
    @Autowired
    MarketBrandMapper marketBrandMapper;
    @Autowired
    MarketGoodsProductMapper marketGoodsProductMapper;
    @Autowired
    ObjectMapper objectMapper;
    @Autowired
    MarketSearchHistoryMapper marketSearchHistoryMapper;
    @Autowired
    MarketFootprintMapper marketFootprintMapper;

    @Override
    public WxGoodsListData wxQuery(BaseParam param, Integer categoryId) {
        //开启分页
        PageHelper.startPage(param.getPage(), param.getLimit());

        List<ListBean> marketGoods = marketGoodsMapper.selectBycategoryId(categoryId);

        MarketCategoryExample categoryExample = new MarketCategoryExample();
        MarketCategoryExample.Criteria criteria = categoryExample.createCriteria();
        criteria.andIdEqualTo(categoryId);
        criteria.andDeletedEqualTo(false);
        List<MarketCategory> marketCategories = marketCategoryMapper.selectByExample(categoryExample);

        // 会去获得一些分页信息
        // 上面的查询对应的PageInfo → 把原始查询结果放入到构造方法里
        PageInfo pageInfo = new PageInfo(marketGoods);

        // total是总的数据量 → 是否等于users.length?不是 → 指的是如果不分页的情况下最多会查询出来多少条记录
        // 按照上面的查询的查询条件执行的select count(*)
        long total = pageInfo.getTotal();
        int pages = pageInfo.getPages();
        return WxGoodsListData.data(total, pages, param.getLimit(), param.getPage(), marketGoods, marketCategories);
    }

    @Override
    public long wxQueryCount() {
        MarketGoodsExample goodsExample = new MarketGoodsExample();
        MarketGoodsExample.Criteria criteria = goodsExample.createCriteria();
        criteria.andDeletedEqualTo(false);
        long count = marketGoodsMapper.countByExample(goodsExample);
        return count;
    }

    @Override
    public WxGoodsRelatedData wxQueryRelated(Integer id) {
        //开启分页
        PageHelper.startPage(1, 6);
        MarketGoods marketGoods = marketGoodsMapper.selectByPrimaryKey(id);
        //获取goods的种类
        Integer categoryId = marketGoods.getCategoryId();
        MarketGoodsExample goodsExample = new MarketGoodsExample();
        MarketGoodsExample.Criteria criteria = goodsExample.createCriteria();
        criteria.andCategoryIdEqualTo(categoryId);
        List<ListBean> list = marketGoodsMapper.selectBycategoryId2(categoryId);

        // 会去获得一些分页信息
        // 上面的查询对应的PageInfo → 把原始查询结果放入到构造方法里
        PageInfo pageInfo = new PageInfo(list);

        // total是总的数据量 → 是否等于users.length?不是 → 指的是如果不分页的情况下最多会查询出来多少条记录
        // 按照上面的查询的查询条件执行的select count(*)
        long total = pageInfo.getTotal();
        int pages = pageInfo.getPages();
        return WxGoodsRelatedData.data(total, pages, 6, 1, list);
    }

    @Override
    public WxGoodsListData wxQuery2(BaseParam param, String keyword, Integer hasId) {
        Integer userId = UserIdUtil.getUserIdFromSubject();
        if (userId != -1) {
            MarketSearchHistoryExample searchHistoryExample = new MarketSearchHistoryExample();
            MarketSearchHistoryExample.Criteria criteria = searchHistoryExample.createCriteria();
            criteria.andKeywordEqualTo(keyword);
            criteria.andDeletedEqualTo(false);
            List<MarketSearchHistory> marketSearchHistories = marketSearchHistoryMapper.selectByExample(searchHistoryExample);
            if (marketSearchHistories.size() == 0) {
                //说明没有搜索过
                MarketSearchHistory marketSearchHistory = new MarketSearchHistory();
                marketSearchHistory.setUserId(userId);
                marketSearchHistory.setKeyword(keyword);
                marketSearchHistory.setAddTime(new Date());
                marketSearchHistory.setUpdateTime(new Date());
                marketSearchHistoryMapper.insertSelective(marketSearchHistory);
            } else {
                MarketSearchHistoryExample marketSearchHistoryExample = new MarketSearchHistoryExample();
                MarketSearchHistoryExample.Criteria criteria1 = marketSearchHistoryExample.createCriteria();
                criteria1.andUserIdEqualTo(userId);
                criteria1.andKeywordEqualTo(keyword);
                MarketSearchHistory marketSearchHistory = new MarketSearchHistory();
                marketSearchHistory.setUpdateTime(new Date());
                marketSearchHistoryMapper.updateByExampleSelective(marketSearchHistory, marketSearchHistoryExample);
            }
        }
        //开启分页
        PageHelper.startPage(param.getPage(), param.getLimit());

        List<ListBean> marketGoods = marketGoodsMapper.selectGoodsByKeyword(param, "%" + keyword + "%");
        if (marketGoods == null || marketGoods.size() == 0) {
            return WxGoodsListData.data(0, 0, param.getLimit(), param.getPage(), null, null);
        }

        MarketGoodsExample goodsExample = new MarketGoodsExample();
        MarketGoodsExample.Criteria criteria = goodsExample.createCriteria();
        criteria.andNameLike("%" + keyword + "%");
        criteria.andDeletedEqualTo(false);
        if (hasId != 0) {
            criteria.andCategoryIdEqualTo(hasId);
        }
        List<MarketGoods> marketGoods1 = marketGoodsMapper.selectByExample(goodsExample);
        ArrayList categoryList = new ArrayList();
        for (MarketGoods goods : marketGoods1) {
            Integer categoryId = goods.getCategoryId();
            categoryList.add(categoryId);
        }
        MarketCategoryExample categoryExample = new MarketCategoryExample();
        MarketCategoryExample.Criteria criteria1 = categoryExample.createCriteria();
        criteria1.andIdIn(categoryList);
        criteria1.andDeletedEqualTo(false);
        List<MarketCategory> marketCategories = marketCategoryMapper.selectByExample(categoryExample);

        // 会去获得一些分页信息
        // 上面的查询对应的PageInfo → 把原始查询结果放入到构造方法里
        PageInfo pageInfo = new PageInfo(marketGoods);

        // total是总的数据量 → 是否等于users.length?不是 → 指的是如果不分页的情况下最多会查询出来多少条记录
        // 按照上面的查询的查询条件执行的select count(*)
        long total = pageInfo.getTotal();
        int pages = pageInfo.getPages();
        return WxGoodsListData.data(total, pages, param.getLimit(), param.getPage(), marketGoods, marketCategories);
    }


    /**
     * @param
     * @Description: goodsDetail请求的实现
     * @return:
     * @Author: 蒋镇泽
     * @Date: 2022/6/8 17:25
     */
    @Override
    public FootPritnByIdVo wxQueryById(Integer id) {
        FootPritnByIdVo footPritnByIdVo = new FootPritnByIdVo();
        //查询spec
        MarketGoodsSpecificationExample marketGoodsSpecificationExample = new MarketGoodsSpecificationExample();
        marketGoodsSpecificationExample.createCriteria().andGoodsIdEqualTo(id);
        List<MarketGoodsSpecification> marketGoodsSpecifications = marketGoodsSpecificationMapper.selectByExample(marketGoodsSpecificationExample);
        ArrayList<FootPritnByIdSpecVo> footPritnByIdSpecValueVos = new ArrayList<>();
        if (marketGoodsSpecifications != null) {
            for (MarketGoodsSpecification specs : marketGoodsSpecifications) {
                FootPritnByIdSpecVo spec = new FootPritnByIdSpecVo();
                spec.setName(specs.getSpecification());
                ArrayList<FootPritnByIdSpecValueVo> footPritnByIdSpecValueVos1 = new ArrayList<>();
                FootPritnByIdSpecValueVo specValueVo = new FootPritnByIdSpecValueVo();
                specValueVo.setId(specs.getId());
                specValueVo.setGoodsId(specs.getGoodsId());
                specValueVo.setSpecification(specs.getSpecification());
                specValueVo.setValue(specs.getValue());
                specValueVo.setPicUrl(specs.getPicUrl());
                specValueVo.setAddTime(specs.getAddTime());
                specValueVo.setUpdateTime(specs.getUpdateTime());
                specValueVo.setDeleted(specs.getDeleted());

                footPritnByIdSpecValueVos1.add(specValueVo);
                spec.setValueList(footPritnByIdSpecValueVos1);
                footPritnByIdSpecValueVos.add(spec);
            }
        }

        footPritnByIdVo.setSpecificationList(footPritnByIdSpecValueVos);
//iss
        ArrayList<FootPritnByIdGroVo> temp = new ArrayList<>();
        footPritnByIdVo.setGroupon(temp);
        //issue
        ArrayList<FootPritnByIdIssVo> footPritnByIdIssVos = new ArrayList<>();
        MarketIssueExample marketIssueExample = new MarketIssueExample();
        List<MarketIssue> marketIssues = marketIssueMapper.selectByExample(marketIssueExample);
        if (marketIssues != null) {
            for (MarketIssue marketIssue : marketIssues) {
                FootPritnByIdIssVo issVo = new FootPritnByIdIssVo();
                issVo.setId(marketIssue.getId());
                issVo.setQuestion(marketIssue.getQuestion());
                issVo.setAnswer(marketIssue.getAnswer());
                issVo.setAddTime(marketIssue.getAddTime());
                issVo.setUpdateTime(marketIssue.getUpdateTime());
                issVo.setDeleted(marketIssue.getDeleted());
                footPritnByIdIssVos.add(issVo);
            }
        }

        footPritnByIdVo.setIssue(footPritnByIdIssVos);
        //是否收藏了,表里没数据
        MarketCollectExample marketCollectExample = new MarketCollectExample();
        Integer userIdFromSubject = UserIdUtil.getUserIdFromSubject();
        if (userIdFromSubject != null) {
            MarketCollectExample.Criteria criteria = marketCollectExample.createCriteria();
            criteria.andUserIdEqualTo(userIdFromSubject);
            criteria.andValueIdEqualTo(id);
            List<MarketCollect> marketCollects = marketCollectMapper.selectByExample(marketCollectExample);
            if (marketCollects != null) {
                for (MarketCollect marketCollect : marketCollects) {
                    Boolean deleted = marketCollect.getDeleted();
                    if (deleted.equals(true)) {
                        footPritnByIdVo.setUserHasCollect(0);
                    } else {
                        footPritnByIdVo.setUserHasCollect(1);
                    }
                }
            } else {
                footPritnByIdVo.setUserHasCollect(0);
            }
        } else {
            footPritnByIdVo.setUserHasCollect(0);
        }


        //不知所云,先放空吧
        String string = "";
        footPritnByIdVo.setShareImage(string);
        //评论可以有
        FootPritnByIdCommentVo footPritnByIdCommentVo = new FootPritnByIdCommentVo();
        MarketCommentExample marketCommentExample = new MarketCommentExample();
        marketCommentExample.createCriteria().andValueIdEqualTo(id);
        List<MarketComment> marketComments = marketCommentMapper.selectByExample(marketCommentExample);
        footPritnByIdCommentVo.setCount(marketComments.size());
        ArrayList<FootPritnByIdCommentDataVo> commentDataVos = new ArrayList<>();
        if (marketComments != null) {
            for (MarketComment marketComment : marketComments) {
                FootPritnByIdCommentDataVo comment = new FootPritnByIdCommentDataVo();
                comment.setAddTime(marketComment.getAddTime());
                comment.setPicList(marketComment.getPicUrls());
                comment.setAdminContent(marketComment.getAdminContent());
                //评论姓名
                MarketUser marketUser = marketUserMapper.selectByPrimaryKey(marketComment.getUserId());
                if (marketUser != null) {
                    comment.setNickname(marketUser.getNickname());
                    comment.setId(marketComment.getId());
                } else {
                    comment.setNickname(null);
                    comment.setId(null);
                }

                //不知道是啥
                comment.setAvatar(null);
                comment.setContent(marketComment.getContent());

                commentDataVos.add(comment);
            }
        }


        footPritnByIdCommentVo.setData(commentDataVos);
        footPritnByIdVo.setComment(footPritnByIdCommentVo);
        //写死
        footPritnByIdVo.setShare(true);
//attribute
        ArrayList<FootPritnByIdAttriVo> footPritnByIdAttriVos = new ArrayList<>();
        MarketGoodsAttributeExample marketGoodsAttributeExample = new MarketGoodsAttributeExample();

        marketGoodsAttributeExample.createCriteria().andGoodsIdEqualTo(id);
        List<MarketGoodsAttribute> marketGoodsAttributes = marketGoodsAttributeMapper.selectByExample(marketGoodsAttributeExample);
        if (marketGoodsAttributes != null) {
            for (MarketGoodsAttribute marketGoodsAttribute : marketGoodsAttributes) {
                FootPritnByIdAttriVo attriVo = new FootPritnByIdAttriVo();
                attriVo.setAddTime(marketGoodsAttribute.getAddTime());
                attriVo.setId(marketGoodsAttribute.getId());
                attriVo.setGoodsId(marketGoodsAttribute.getGoodsId());
                attriVo.setAttribute(marketGoodsAttribute.getAttribute());
                attriVo.setValue(marketGoodsAttribute.getValue());
                attriVo.setUpdateTime(marketGoodsAttribute.getUpdateTime());
                attriVo.setDeleted(marketGoodsAttribute.getDeleted());
                footPritnByIdAttriVos.add(attriVo);
            }
        }

        footPritnByIdVo.setAttribute(footPritnByIdAttriVos);
        //product
        MarketGoodsProductExample marketGoodsProductExample = new MarketGoodsProductExample();
        marketGoodsProductExample.createCriteria().andGoodsIdEqualTo(id);
        List<MarketGoodsProduct> marketGoodsProducts = marketGoodsProductMapper.selectByExample(marketGoodsProductExample);
        ArrayList<FootPritnByIdProVo> footPritnByIdProVos = new ArrayList<>();
        if (marketGoodsProducts != null) {
            for (MarketGoodsProduct goodsProduct : marketGoodsProducts) {
                FootPritnByIdProVo proVo = new FootPritnByIdProVo();
                proVo.setId(goodsProduct.getId());
                proVo.setGoodsId(goodsProduct.getGoodsId());
                String[] specifications = goodsProduct.getSpecifications();
                // String[] strings = new String[1];
                // try {
                //     strings = objectMapper.readValue(specifications, String[].class);
                // } catch (IOException e) {
                //
                // }
                proVo.setSpecifications(specifications);
                proVo.setPrice(goodsProduct.getPrice());
                proVo.setNumber(goodsProduct.getNumber());
                proVo.setUrl(goodsProduct.getUrl());
                proVo.setAddTime(goodsProduct.getAddTime());
                proVo.setUpdateTime(goodsProduct.getUpdateTime());
                proVo.setDeleted(goodsProduct.getDeleted());
                footPritnByIdProVos.add(proVo);
            }
        }
        footPritnByIdVo.setProductList(footPritnByIdProVos);
        //info
        MarketGoods marketGoods = marketGoodsMapper.selectByPrimaryKey(id);
        FootPritnByIdInfoVo infoVo = new FootPritnByIdInfoVo();
        if (marketGoods != null) {
            infoVo.setId(marketGoods.getId());
            infoVo.setGoodsSn(marketGoods.getGoodsSn());
            infoVo.setName(marketGoods.getName());
            infoVo.setCategoryId(marketGoods.getCategoryId());
            infoVo.setBrandId(marketGoods.getBrandId());
            infoVo.setGallery(marketGoods.getGallery());
            infoVo.setKeywords(marketGoods.getKeywords());
            infoVo.setBrief(marketGoods.getBrief());
            infoVo.setIsOnSale(marketGoods.getIsOnSale());
            infoVo.setSortOrder(Integer.valueOf(marketGoods.getSortOrder()));
            infoVo.setPicUrl(marketGoods.getPicUrl());
            infoVo.setShareUrl(marketGoods.getShareUrl());
            infoVo.setIsNew(marketGoods.getIsNew());
            infoVo.setIsHot(marketGoods.getIsHot());
            infoVo.setUnit(marketGoods.getUnit());
            infoVo.setCounterPrice(marketGoods.getCounterPrice());
            infoVo.setRetailPrice(marketGoods.getRetailPrice());
            infoVo.setAddTime(marketGoods.getAddTime());
            infoVo.setUpdateTime(marketGoods.getUpdateTime());
            infoVo.setDeleted(marketGoods.getDeleted());
            infoVo.setDetail(marketGoods.getDetail());
        }

        footPritnByIdVo.setInfo(infoVo);
        //brand
        FootPritnByIdBrandVo footPritnByIdBrandVo = new FootPritnByIdBrandVo();
        MarketBrand marketBrand = marketBrandMapper.selectByPrimaryKey(marketGoods.getBrandId());
        if (marketBrand != null) {
            footPritnByIdBrandVo.setId(marketBrand.getId());
            footPritnByIdBrandVo.setName(marketBrand.getName());
            footPritnByIdBrandVo.setDesc(marketBrand.getDesc());
            footPritnByIdBrandVo.setPicUrl(marketBrand.getPicUrl());
            footPritnByIdBrandVo.setSortOrder(Integer.valueOf(marketBrand.getSortOrder()));
            footPritnByIdBrandVo.setFloorPrice(marketBrand.getFloorPrice());
            footPritnByIdBrandVo.setAddTime(marketBrand.getAddTime());
            footPritnByIdBrandVo.setUpdateTime(marketBrand.getUpdateTime());
            footPritnByIdBrandVo.setDeleted(marketBrand.getDeleted());
        }
        footPritnByIdVo.setBrand(footPritnByIdBrandVo);
//查看商品详情页添加历史记录
        Subject subject = SecurityUtils.getSubject();
        MarketUser primaryPrincipal = null;
        if (subject.isAuthenticated()) {
            PrincipalCollection principals = subject.getPrincipals();
            if (principals != null) {
                primaryPrincipal = (MarketUser) principals.getPrimaryPrincipal();
            }
        }
        Integer userId = 0;

        if (primaryPrincipal != null) {
            userId = primaryPrincipal.getId();
            Date date = new Date();
            MarketFootprint marketFootprint = new MarketFootprint();
            marketFootprint.setId(null);
            marketFootprint.setUserId(userId);
            marketFootprint.setGoodsId(id);
            marketFootprint.setAddTime(date);
            marketFootprint.setUpdateTime(date);
            marketFootprint.setDeleted(false);
            marketFootprintMapper.insertSelective(marketFootprint);
        }


        return footPritnByIdVo;
    }


}